import React, { useEffect, useState } from 'react'
import useForm from "rc-form-hooks"
import { connect } from 'dva'
import { Form, Input, DatePicker, Button, Select, message } from 'antd'
import moment from 'moment'
import './index.styl'
import { banBackSpace } from 'utils/backspaceFool'

const { Option } = Select

function HeaderSearch({ type, dispatch, searchBtn, query, deviceRepair: { stateOptions2 } }) {

    (function () {
        //实现对字符码的截获，keypress中屏蔽了这些功能按键
        document.onkeypress = banBackSpace;
        //对功能按键的获取
        document.onkeydown = banBackSpace;
    })()
    const { getFieldDecorator, validateFields, resetFields, setFieldsValue } = useForm()
    // 获取状态选项
    useEffect(() => {
        dispatch({
            type: 'deviceRepair/getReftStatusAll',
        })
        // 没有关闭页面得前提下，是否有缓存，有则优先给表单赋值缓存数据
        const reformSingle = localStorage.getItem('reformSingle')
        if (reformSingle) {
            let newData = JSON.parse(reformSingle)
            let datas = {
                ...newData,
                repairStartTime: newData['repairStartTime'] && moment(newData['repairStartTime']),
                repairEndTime: newData['repairEndTime'] && moment(newData['repairEndTime']),
            }
            setFieldsValue(datas)
        }
    }, [dispatch, getStatusOptions, query.codeText, setFieldsValue, type])

    const getStatusOptions = {
        'repairSingle': 'deviceRepair/getRepairStatus', // 维修
        'reformSingle': 'deviceRepair/getReftStatusAll', // 整改
        'complainSingle': 'deviceRepair/getComplaintStatus', // 整改
    }

    const actions = {
        'repairSingle': 'deviceRepair/getSingleList', // 维修
        'reformSingle': 'deviceRepair/getReftList', // 整改
        'complainSingle': 'deviceRepair/getComplaintList', // 投诉
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        validateFields()
            .then((values) => {
                searchBtn({
                    ...values,
                    repairStartTime: values['repairStartTime'] && values['repairStartTime'].format('YYYY-MM-DD'),
                    repairEndTime: values['repairEndTime'] && values['repairEndTime'].format('YYYY-MM-DD'),
                    current: '1',
                    size: '10',
                })
            })
            .catch(e => message.error(e.message))
    }

    // 选择时间对应的模块标题
    const timeTitle = {
        'repairSingle': '报修时间',
        'reformSingle': '整改截止时间',
        'complainSingle': '投诉时间',
    }

    // 开始时间
    const [startTime, setStartTime] = useState()

    // 结束时间
    const [endTime, setEndTime] = useState()

    // 重置
    const onReset = () => {
        setStartTime()
        setEndTime()
        resetFields();
        // 清除缓存数据
        dispatch({ type: 'deviceRepair/clean' })
        // 清除本地缓存
        localStorage.removeItem('reformSingle')
        localStorage.removeItem('reformData')
        searchBtn({
            deviceName: '',//设备名称
            groupName: '',//使用部门
            repairClerk: '',//报修员
            repairman: '',//维修员
            repairmanTel: '',//维修员电话
            state: '', //状态
            repairStartTime: '',//开始时间
            repairEndTime: '',//结束时间
            current: '1',// 当前页码
            size: '10',
        })
        // dispatch({
        //     type: actions[type],
        //     payload: {
        //         current: '1',
        //         size: '10'
        //     }
        // });
    }

    // 开始时间
    const selectStartTime = (time) => {
        setStartTime(time)
    }

    // 开始时间
    const selectEndTime = (time) => {
        setEndTime(time)
    }

    // 设置开始不能选择的时间
    const disabledStartDate = startTime => {
        if (!startTime || !endTime) {
            return false
        }
        return startTime.valueOf() > endTime.valueOf()
    }

    //设置结束不能选择的时间
    const disabledEndDate = endTime => {
        if (!endTime || !startTime) {
            return false
        }
        return endTime.valueOf() <= startTime.valueOf()
    }

    // 实时缓存数据
    const seaveData = (value, name) => {
        const reformSingle = localStorage.getItem('reformSingle')
        if (reformSingle) {
            let data = JSON.parse(reformSingle)
            data[`${name}`] = value
            localStorage.setItem('reformSingle', JSON.stringify(data))
        } else {
            let data = {}
            data[`${name}`] = value
            localStorage.setItem('reformSingle', JSON.stringify(data))
        }
    }

    return (
        <div className="equipmentMaintenance-form">
            <Form name="nest-messages" className="self-form" onSubmit={handleSubmit}>
                <div className="flex flex1">
                    <Form.Item label="设备名称" colon={false}>
                        {getFieldDecorator('deviceName', {
                            rules: [{ required: false }],
                        })(
                            <Input
                                className="self-input"
                                placeholder="请输入"
                                onChange={(e) => seaveData(e.target.value, 'deviceName')}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="设备使用部门" colon={false}>
                        {getFieldDecorator('groupName', {
                            rules: [{ required: false }],
                        })(
                            <Input
                                className="self-input"
                                placeholder="请输入"
                                onChange={(e) => seaveData(e.target.value, 'groupName')}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="报修员" colon={false}>
                        {getFieldDecorator('repairClerk', {
                            rules: [{ required: false }],
                        })(
                            <Input
                                className="self-input"
                                placeholder="请输入"
                                onChange={(e) => seaveData(e.target.value, 'repairClerk')}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="维修员" colon={false}>
                        {getFieldDecorator('repairman', {
                            rules: [{ required: false }],
                        })(
                            <Input
                                className="self-input"
                                placeholder="请输入"
                                onChange={(e) => seaveData(e.target.value, 'repairman')} />
                        )}
                    </Form.Item>
                    <Form.Item label="维修员电话" colon={false}> 
                        {getFieldDecorator('repairmanTel', {
                            rules: [{ required: false }],
                        })(
                            <Input
                                className="self-input"
                                placeholder="请输入"
                                rows={10}
                                onChange={(e) => seaveData(e.target.value, 'repairmanTel')}
                            />
                        )}
                    </Form.Item>
                </div>
                <div className="flex flex2">
                    <Form.Item label="状态" style={{ display: type === 'complainSingle' ? 'none' : '' }} colon={false}>
                        {getFieldDecorator('state', {
                            initialValue: '',
                            rules: [{ required: false }],
                        })(
                            <Select
                                placeholder="Select province"
                                className="self-select"
                                placeholder="请选择"
                                onChange={(value) => seaveData(value, 'state')}
                                getPopupContainer={triggerNode => triggerNode.parentNode}
                            >
                                <Option value=''>全部</Option>
                                {
                                    type !== 'complainSingle' && stateOptions2 && stateOptions2.map((item) => {
                                        return (<Option value={item.code} key={item.code}>{item.message}</Option>)
                                    })
                                }
                            </Select>
                        )}
                    </Form.Item>
                    <Form.Item label={timeTitle[type]} colon={false}>
                        {getFieldDecorator('repairStartTime', {
                            rules: [{ required: false }],
                        })(
                            <DatePicker
                                className="self-date"
                                showToday={false}
                                placeholder="选择开始时间"
                                onChange={selectStartTime}
                                disabledDate={disabledStartDate}
                                allowClear={false}
                                onChange={(e, str) => seaveData(str, 'repairStartTime')}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="">
                        {getFieldDecorator('repairEndTime', {
                            rules: [{ required: false }],
                        })(
                            <DatePicker
                                className="self-date"
                                showToday={false}
                                placeholder="选择结束时间"
                                disabledDate={disabledEndDate}
                                onChange={selectEndTime}
                                allowClear={false}
                                onChange={(e, str) => seaveData(str, 'repairEndTime')}
                            />
                        )}
                    </Form.Item>
                    <Form.Item>
                        <Button className="blue-button" htmlType="submit">查询</Button>
                        <Button className="white-button" onClick={() => onReset()}>重置</Button>
                    </Form.Item>
                </div>
            </Form>
        </div>
    )
}

export default connect(({ deviceRepair }) => ({
    deviceRepair
}))(HeaderSearch)